/**
 * 统一权限检查Hook - 基于权限继承模型
 */

import { useMemo } from 'react';
import { useAuth } from '../contexts/AuthContext';
import PermissionHelper from '../utils/permissionHelper';

/**
 * 权限检查Hook
 */
export const usePermission = () => {
  const auth = useAuth();
  const { user, permissions, isAuthenticated } = auth.state;
  
  // 创建权限检查器实例
  const permissionChecker = useMemo(() => {
    const userPermissions = permissions || [];

    return new PermissionHelper(userPermissions);
  }, [permissions]);

  return useMemo(() => ({
    /**
     * 检查是否有指定权限
     */
    hasPermission: (permission: string): boolean => {
      if (user?.is_superuser) return true;
      return permissionChecker.hasPermission(permission);
    },

    /**
     * 检查是否有任一权限
     */
    hasAnyPermission: (permissions: string[]): boolean => {
      if (user?.is_superuser) return true;
      return permissionChecker.hasAnyPermission(permissions);
    },

    /**
     * 检查是否有所有权限
     */
    hasAllPermissions: (permissions: string[]): boolean => {
      if (user?.is_superuser) return true;
      return permissionChecker.hasAllPermissions(permissions);
    },

    /**
     * 检查是否能对指定资源执行指定操作
     */
    canPerformAction: (resource: string, action: string): boolean => {
      if (user?.is_superuser) return true;
      return permissionChecker.canPerformAction(resource, action);
    },

    /**
     * 检查是否能访问指定页面
     */
    canAccessPage: (pagePath: string): boolean => {
      if (user?.is_superuser) return true;
      return permissionChecker.canAccessPage(pagePath);
    },

    /**
     * 获取对指定资源的可用操作
     */
    getAvailableActions: (resource: string): string[] => {
      if (user?.is_superuser) {
        // 超级用户拥有所有操作权限
        return ['view', 'create', 'update', 'delete', 'manage', 'export', 'import'];
      }
      return permissionChecker.getAvailableActions(resource);
    },

    /**
     * 获取用户的所有有效权限
     */
    getAllEffectivePermissions: (): string[] => {
      return permissionChecker.getAllEffectivePermissions();
    },

    /**
     * 权限调试信息
     */
    getDebugInfo: () => {
      return permissionChecker.getDebugInfo();
    },

    /**
     * 当前用户信息
     */
    user: user,

    /**
     * 是否已认证
     */
    isAuthenticated: isAuthenticated,

    /**
     * 是否为超级用户
     */
    isSuperUser: user?.is_superuser || false
  }), [permissionChecker, user, isAuthenticated]);
};

/**
 * 页面级权限检查Hook
 */
export const usePagePermission = (requiredPermission: string) => {
  const { hasPermission, canAccessPage } = usePermission();
  
  return {
    hasAccess: hasPermission(requiredPermission),
    canAccess: canAccessPage(window.location.pathname),
    requiredPermission
  };
};

/**
 * 资源操作权限检查Hook
 */
export const useResourcePermission = (resource: string) => {
  const { canPerformAction, getAvailableActions } = usePermission();
  
  return {
    canView: canPerformAction(resource, 'view'),
    canCreate: canPerformAction(resource, 'create'),
    canUpdate: canPerformAction(resource, 'update'),
    canDelete: canPerformAction(resource, 'delete'),
    canManage: canPerformAction(resource, 'manage'),
    canExport: canPerformAction(resource, 'export'),
    availableActions: getAvailableActions(resource),
    
    // 便捷方法
    canPerform: (action: string) => canPerformAction(resource, action)
  };
};

/**
 * 权限守卫Hook - 用于路由保护
 */
export const usePermissionGuard = (requiredPermissions: string | string[]) => {
  const { hasPermission, hasAnyPermission } = usePermission();
  
  const permissions = Array.isArray(requiredPermissions) ? requiredPermissions : [requiredPermissions];
  const hasAccess = permissions.length === 1 
    ? hasPermission(permissions[0])
    : hasAnyPermission(permissions);
  
  return {
    hasAccess,
    requiredPermissions: permissions,
    redirectTo: hasAccess ? null : '/403' // 无权限时重定向到403页面
  };
};

export default usePermission;
